/*
 * @Author: 老刘
 * @Date: 2020-04-29 15:51:38
 * @Description: 保存图片
 */
// https://file.cyzl.com/g001/M07/64/21/oYYBAGFRgfOAbUBvAADGPVtRRBg889.jpg
import {alert, haveAuth, openSetting, showToastNoIcon, wxApi2Promise} from '../../../utils/util';

Page({
	data: {
		initFinished: false,
		qrCode: 'https://file.cyzl.com/g001/M07/64/21/oYYBAGFRgdaAOeI8AAAG4yboB50756.png',
		miniCode: '/mini_code/code.jpg',
		qrPath: ''
	},
	async onLoad () {
		await this.startDownloadPic();
	},
	// 处理网络图片路径
	getFilePath (path) {
		return wx.env.USER_DATA_PATH + '/' + path.substring(path.lastIndexOf('/'));
	},
	// 生成本地目录图片
	async startDownloadPic () {
		// 将网络图片转成本地图片,再下载
		try {
			// 需将下载的网络图片添加到开发管理的downloadFile合法域名中
			let qrPath = await wxApi2Promise(wx.downloadFile, { url: this.data.qrCode, filePath: this.getFilePath(this.data.qrCode) });
			this.setData({
				qrPath: qrPath.filePath,
				initFinished: true
			});
		} catch (e) {
			console.log(e);
			showToastNoIcon('生成本地图片失败，请重试');
		}
	},
	async saveImage (e) {
		const type = +e.currentTarget.dataset.type;
		try {
			const url = type === 2 ? this.data.miniCode : (this.data.qrPath ? this.data.qrPath : '../assets/qr_code.png');
			await wxApi2Promise(wx.saveImageToPhotosAlbum, { filePath: url });
			wx.showToast({
				icon: 'success',
				title: '保存成功'
			});
		} catch (e) {
			console.log(e);
			if (!await haveAuth('scope.writePhotosAlbum')) {
				alert({
					content: '检查您未授权保存图片，请授权',
					showCancel: true,
					confirmText: '授权',
					confirm: async () => {
						await openSetting();
					}
				});
				return;
			}
			showToastNoIcon('保存图片失败，请重试');
		}
	}
});
